<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>放大镜右侧显示</title>
</head>
<style>
    .main {
        position: relative;
    }

    .product {
        width: 400px;
        height: 400px;
        border: 1px solid grey;
        background: url(./assets/phone.jpg) no-repeat 100% 100%;
    }

    .area {
        display: none;
        position: absolute;
        width: 200px;
        height: 200px;
        background-color: rgb(218, 165, 32, .6);
        cursor: move;
    }

    .zoom-box {
        display: none;
        position: absolute;
        top: 0;
        left: 400px;
        width: 500px;
        height: 500px;
        border: 1px solid grey;

        overflow: hidden;
    }

    .zoom-pic {
        position: absolute;
        width: 800px
    }
</style>

<body>
    <div class="main">
        <div class="product">
            <div class="area"></div>
        </div>
        <div class="zoom-box">
            <img class="zoom-pic" src="./assets/phone.jpg">
        </div>
    </div>
</body>

<script>
    let product = document.querySelector('.product')
    let area = document.querySelector('.area')
    let zoomBox = document.querySelector('.zoom-box')
    let zoomPic = document.querySelector('.zoom-pic')

    product.onmouseover = function () {
        area.style.display = 'block'
        zoomBox.style.display = 'block'
    }
    product.onmouseout = function () {
        area.style.display = 'none'
        zoomBox.style.display = 'none'
    }
    product.onmousemove = function (e) {
        let left = e.clientX - area.clientWidth / 2
        let top = e.clientY - area.clientHeight / 2

        if (left < 0) {
            left = 0
        } else if (left > product.clientWidth - area.clientWidth) {
            left = product.clientWidth - area.clientWidth
        }
        if (top < 0) {
            top = 0
        } else if (top > product.clientHeight - area.clientHeight) {
            top = product.clientHeight - area.clientHeight
        }

        area.style.left = left + 'px'
        area.style.top = top + 'px'

        let percentWidth = left / (product.clientWidth - area.clientWidth)
        let zoomLeft = percentWidth * (zoomPic.clientWidth - zoomBox.clientWidth)

        let percentHeight = top / (product.clientHeight - area.clientHeight)
        let zoomTop = percentHeight * (zoomPic.clientHeight - zoomBox.clientHeight)

        zoomPic.style.left = -zoomLeft + 'px'
        zoomPic.style.top = -zoomTop + 'px'
    }

</script>

</html>